﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using HigLabo.Net.Extensions;

namespace HigLabo.Net.Facebook
{
    /// <summary>
    /// 
    /// </summary>
    public class FacebookResponseException : Exception
    {
        /// <summary>
        /// 
        /// </summary>
        public String ErrorMessage { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public String ErrorType { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public Int32 ErrorCode { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public HttpResponse HttpResponse { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        public HttpWebResponse Response { get; private set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="exception"></param>
        public FacebookResponseException(WebException exception)
            : base(exception.Message, exception)
        {
            this.Response = exception.Response as HttpWebResponse;
            this.HttpResponse = new HttpResponse(this.Response, Encoding.UTF8);
            var d = JsonConvert.DeserializeObject<Dictionary<String, Object>>(this.HttpResponse.BodyText);
            d = JsonConvert.DeserializeObject<Dictionary<String, Object>>(d.ToString("error"));
            this.ErrorMessage = d.ToString("message");
            this.ErrorType = d.ToString("type");
            this.ErrorCode = d.ToInt32("code") ?? this.ErrorCode;
        }
    }
}
